package com.qqclient.service;
//
import com.qqcommon.Message;
import com.qqcommon.MessageType;
import com.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

//根据提供的User，pwd，完成用户登录验证
public class UserClinentService {
    Boolean b = false;
    private   User u=new User();
    private Socket socket;

    public Boolean checkUser(String userId,String pwd) throws IOException, ClassNotFoundException {
        u.setUserId(userId);
        u.setPasswd(pwd);
        //连接服务端，发送信息
        socket = new Socket(InetAddress.getLocalHost(), 9999);
        ObjectOutputStream oss = new ObjectOutputStream(socket.getOutputStream());
        //向服务端发送信息，进行验证
        oss.writeObject(u);
        //接受服务端传回的信息
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        Message ms =(Message) ois.readObject();
        if (ms.getMesType().equals(MessageType.MESSAGE_LOGIN_SUCCEED)){
            //验证通过，进行线程
            ClientConnectServerThrend clientConnectServerThrend = new ClientConnectServerThrend(socket);
            //启动客户端线程
            clientConnectServerThrend.start();
            //将线程放入到ManageClinentConnectServerThrend的HashMap
            ManageClinentConnectServerThrend.addClinentConnectServerThrend(userId,clientConnectServerThrend);
            b=true;
        }else {
            //验证失败
            socket.close();
        }
        return b;
    }
    //服务器端请求在线用户列表
    public void onlineFriendList() throws IOException {
        //发送Message给服务端
        Message message = new Message();
        message.setMesType(MessageType.MESSAGE_GET_ONLINE_FRIEND);
        message.setSender(u.getUserId());
        //得到当前线程
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(ManageClinentConnectServerThrend.getClinentConnectServerThrend(u.getUserId()).getSocket().getOutputStream());
        //得到当前线程，向服务端发送在线请求
        objectOutputStream.writeObject(message);

    }
    //编写方法退出客户端，并且向服务端发送退出系统的Message对象
    public void logcut() throws IOException {
        Message message = new Message();
        message.setMesType(MessageType.MESSAGE_CLIENT_EXIT);
        //向服务端指出要退出的线程
        message.setSender(u.getUserId());
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        objectOutputStream.writeObject(message);
        System.out.println(u.getUserId()+" 退出系统");
        System.exit(0);
    }

}
